<template>
  <el-dialog :title="form.id == 0?'新增':'更新'" :visible.sync="showFlag.status">
    <el-form :model="form" label-width="100px" :rules="rules">
      <el-form-item label="属性名" prop="specsname">
        <el-input v-model="form.specsname" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="属性值">
        <div class="item" v-for="(line,index) in attrs" :key="index">
            <el-input autocomplete="off" v-model="attrs[index]"></el-input>
            <el-button v-if="index == 0" type="success" @click="addAttr">添加</el-button>
            <el-button v-else type="danger" @click="delAttr(index)">删除</el-button>
        </div>    
      </el-form-item>      
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :label="1">正常</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button>取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import vm from "../../vm/vm"
export default {
  created(){
    vm.$on("specsEdit",(result)=>{
      console.log(result)
      //打开模态框
      this.showFlag.status = true
      //设置数据
      this.form = result
      this.attrs = result.attrs
    })
  },
  props: ['showFlag'],
  methods: {
      delAttr(index){
        this.attrs.splice(index,1)
      },
      submit(){
          this.form["attrs"] = this.attrs.join(",")
          console.log(this.form)
           
          const url = this.form.id == 0?'"/specsadd"':'/specsedit'
          this.$http.post(url,this.form).then(
              res=>{
                  if(res.status == 200){
                      this.form = {
                        specsname: "",
                        attrs: "",
                        status: 1
                      }
                      this.attrs = [""]
                      this.showFlag.status = false
                      this.$emit("updateSpecs")
                  }
              }
          )
      },
      addAttr(){
          if(this.attrs.length < 5){
              this.attrs.push("")
          }else{
              alert("最多添加5个属性")
          }
      }
  },  
  data() {
    return {
      attrs: [""],  
      form: {
        id: 0,
        specsname: "",
        attrs: "",
        status: 1
      },
      rules: {
          specsname: {required: true,message: "规格名称不可以为空",trigger: "blur"},
          status: {required: true,message: "规格状态不可以为空",trigger: "blur"},
      }
    };
  }
};
</script>

<style scoped>
    .item{
        display: flex;
        margin-bottom: 5px;
    }
    .item>input,.item>button{
        margin: 0 5px;
    }
</style>